package cn.yuanqiao.archive.webservice.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.uploadfile.service.impl.FileService;
import cn.yuanqiao.archive.webservice.service.ArchiveEnhanceService;
import cn.yuanqiao.archive.webservice.utils.WebServiceFileUtils;
import cn.yuanqiao.archive.webservice.utils.XMLtoJsonUtils;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.utils.FileUploadUtils;
import cn.yuanqiao.auth.util.TokenParamUtil;
import cn.yuanqiao.common.core.domain.BusinessActivity;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.feignService.AsyncLogService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArchiveEnhanceServiceImpl implements ArchiveEnhanceService {
    private final Logger logger = LoggerFactory.getLogger(ArchiveEnhanceServiceImpl.class);
    @Value("${onLineArchive.Path}")
    private String onLineArchivePath;
    @Value("${onLineArchive.Charset}")
    private String onLineArchiveCharset;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;
    @Autowired
    private TenantSysDictDataMapper tenantSysDictDataMapper;
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private TenantYqItemMapper itemMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantItemFolderMapper itemFolderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private TenantYqdaDocumentMapper tenantYqdaDocumentMapper;
    @Autowired
    private TenantYqdaMapper tenantYqdaMapper;
    @Autowired
    private TenantYqdaFolderMapper yqdaFolderMapper;
    @Autowired
    private TenantSysConfigMapper tenantSysConfigMapper;
    @Autowired
    private AsyncLogService asyncLogService;

    private static DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional
    public String saveArchiveEnhance(String archiveCode,String archiveType, String fileMD5, String data) {
        JSONObject msg = new JSONObject();
        msg.put("code",500);
        try {
            logger.info("archiveCode={}",archiveCode);
            String archive = new String(Base64Utils.decodeFromString(archiveCode));
            logger.info("archive={}",archive);//{"categoryId":"123456789","tenantCode":"A001"}
            logger.info("fileMD5={}",fileMD5);
            if(StringUtils.isNotEmpty(onLineArchivePath)){
                JSONObject info = JSONObject.parseObject(archive);
                info.put("archiveType",archiveType);
                String path = onLineArchivePath+fileMD5+".zip";  //归档包保存路径
                logger.info("path={}",path);
                WebServiceFileUtils.base64ToFile(data,new File(path));  //base64转文件
                String md5 = WebServiceFileUtils.getFileMD5(new File(path));  //获取文件MD5
                if(fileMD5.equals(md5)){
                    onLineArchiveCharset = StringUtils.isNotEmpty(onLineArchiveCharset) ? onLineArchiveCharset:"UTF-8";  //解压文件编码
                    logger.info("onLineArchiveCharset={}",onLineArchiveCharset);
                    String unzipPath = onLineArchivePath+fileMD5;   //解压文件路径
                    logger.info("unzipPath={}",unzipPath);
                    FileService.decompress(path,unzipPath,onLineArchiveCharset);  //解压文件

                    Long categoryId = info.getLong("categoryId");
                    String tenantCode = info.getString("tenantCode");
                    TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId,tenantCode+TenantCategory.BIGTABLENAME);
                    logger.info(category.toString());

                    traverseFiles(new File((unzipPath)),info,msg,category);  //遍历文件
                    FileUtils.deleteQuietly(new File(unzipPath));//删除文件
                    msg.put("code",200);
                }else {
                    msg.put("code",502);
                    msg.put("msg","文件MD5值不一致！");
                    //logger.error("文件MD5值不一致！");
                    //throw new ServiceException("文件MD5值不一致");
                }
            }else {
                msg.put("code",501);
                throw new ServiceException("在线移交包路径未配置");
                //logger.error("在线移交包路径未配置！");
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚事务
            if(e instanceof ServiceException && e.getMessage().indexOf("文件获取失败")>-1){
                msg.put("code",503);
                msg.put("msg","缺少电子文件！");
            }else if(e instanceof ServiceException){
                msg.put("code",999);
                msg.put("msg",e.getMessage());
            }
        }
        logger.info("return={}",msg.toJSONString());
        return msg.toJSONString();
    }


    /**
     * 遍历文件
     * @param directory
     * @param info
     * @param msg
     * @throws Exception
     */
    private void traverseFiles(File directory,JSONObject info,JSONObject msg,TenantCategory category) throws Exception {
        Integer type = info.getInteger("archiveType");
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    traverseFiles(file,info,msg,category);
                }
            }
        } else {
            //文件类型
            if(type == 2){
                if("project.xml".equals(directory.getName())) {
                    analysisArchive(directory,info,msg,category);
                }
            }else if(type == 1){
                if("metadata.xml".equals(directory.getName())) {
                    analysisArchive(directory,info,msg,category);
                }
            }else if(type == 0){
                if("metadata.xml".equals(directory.getName())) {
                    analysisArchive(directory,info,msg,category);
                }
            }
        }
    }

    private Map<String,String> getValByMdataList(Map<String,String> colData,JSONObject archiveInfo,List<TenantMdataList> mdataLists,Integer oaType,String tenantCode){
        for(TenantMdataList mdataList:mdataLists) {  //循环电子文件层元数据方案
            //处理机构问题特殊符号转义的问题（农发项目专用）
            if(mdataList.getFieldCaption().equals("机构（问题）")){
                String str = "机构问题";
                if(mdataList.getType() == oaType && archiveInfo.containsKey(str)){
                    colData.put(mdataList.getFieldName(),archiveInfo.getString(str));
                }
            }
            //处理合同金额万元特殊符号转义的问题（农发项目专用）
            if(mdataList.getFieldCaption().equals("合同金额（万元）")){
                String str = "合同金额万元";
                if(mdataList.getType() == oaType && archiveInfo.containsKey(str)){
                    colData.put(mdataList.getFieldName(),archiveInfo.getString(str));
                }
            }
            if(mdataList.getType() == oaType && archiveInfo.containsKey(mdataList.getFieldCaption())){
                colData.put(mdataList.getFieldName(),archiveInfo.getString(mdataList.getFieldCaption()));   //先赋值
                if(mdataList.getShowType() == 5){
                    List<TenantSysDictData> dictDatas = tenantSysDictDataMapper.selectDictDataByType(mdataList.getFieldName(),tenantCode+TenantSysDictData.BIGTABLENAME);
                    for(TenantSysDictData sysDictData:dictDatas){
                        if(sysDictData.getDictLabel().equals(archiveInfo.getString(mdataList.getFieldCaption()))){
                            colData.put(mdataList.getFieldName(),sysDictData.getDictValue());  //字典项值覆盖
                            break;
                        }
                    }
                }else if(mdataList.getShowType() == 1){
                    if(archiveInfo.getString(mdataList.getFieldCaption()) == null || "".equals(archiveInfo.getString(mdataList.getFieldCaption()).trim())){
                        //colData.put(mdataList.getFieldName(),"0");
                        colData.remove(mdataList.getFieldName());
                    }
                }
                if(oaType == 1 || oaType == 0){
                    if((mdataList.getFieldName().equals("GDSJ") || mdataList.getFieldName().equals("GDCS")) && StringUtils.isNotEmpty(archiveInfo.getString(mdataList.getFieldCaption()))){
                        Long deptId = archiveMapper.getDeptIdByName(archiveInfo.getString(mdataList.getFieldCaption()),tenantCode);
                        if(deptId !=null){
                            colData.put(mdataList.getFieldName()+"_ID", String.valueOf(deptId));
                        }
                    }
                    if(mdataList.getFieldName().equals("JBR") && StringUtils.isNotEmpty(archiveInfo.getString(mdataList.getFieldCaption()))){
                        Long userId = archiveMapper.getUserIdByName(archiveInfo.getString(mdataList.getFieldCaption()),tenantCode);
                        if(userId !=null){
                            colData.put(mdataList.getFieldName()+"_ID", String.valueOf(userId));
                            colData.put("CREATE_ID", String.valueOf(userId));
                            colData.put("CREATE_BY", archiveInfo.getString(mdataList.getFieldCaption()));

                        }
                    }
                }

            }
        }
        return colData;
    }

    /**
     * 解析数据
     * @param xmlFile
     * @param info
     * @param msg
     * @throws Exception
     */
    private void analysisArchive(File xmlFile,JSONObject info,JSONObject msg,TenantCategory category) throws Exception{
        JSONObject archiveData = XMLtoJsonUtils.startXMLToJSON(xmlFile);  //xml 文件解析成 JSON格式
        logger.info(archiveData.toJSONString());
        String tenantCode = info.getString("tenantCode");
        TenantMdataList selectMdtaList = new TenantMdataList();
        selectMdtaList.setGroupId(category.getGroupId());
        selectMdtaList.setTableName(tenantCode+TenantMdataList.BIGTABLENAME);
        List<TenantMdataList> mdataLists = tenantMdataListMapper.selectTenantMdataListList(selectMdtaList);
        Long itemId = null;
        Integer archiveType = info.getInteger("archiveType");
        if(archiveType == 2){
            //解析项目层
            JSONObject archiveInfo = archiveData;
            //确定项目唯一
            if(!archiveInfo.containsKey("项目编号")){
                throw new ServiceException("缺少必要参数<项目编号>");
            }
            String XMBH = archiveInfo.getString("项目编号");
            Long itemIdArchive = archiveMapper.getItemIdByXMBH(XMBH,category.getItemTableName());
            if(itemIdArchive == null){
                Map<String,String> colData = new HashMap<>();
                //根据元数据解析节点
                colData.putAll(getValByMdataList(colData,archiveInfo,mdataLists,3,tenantCode));
                itemId = SnowflakeIdGenerator.generateId();
                colData.put("ID", String.valueOf(itemId));
                colData.put("IS_DEL","0");
                colData.put("IS_INDEX","0");
                colData.put("STATE","1");
                colData.put("JS_TYPE","1");  //在线移交
                TenantYqItem item = new TenantYqItem();
                item.setColNames(colData);
                item.setTableName(category.getItemTableName());
                itemMapper.insertItem(item);
                colData.put("SUB_TABLE_NAME", category.getItemTableName());
                colData.remove("ID");
                colData.put("ITEM_ID", String.valueOf(itemId));
                item.setColNames(colData);
                item.setTableName(tenantCode+TenantYqItem.BIGTABLENAME);
                int r = itemMapper.insertItem(item); //插入总表
            }else {
                itemId = itemIdArchive;
            }
        }
        Long folderId = null;
        if(archiveType == 2 || archiveType == 1){
            JSONObject archiveInfo = null;
            if(archiveType == 2){
                File juanXml = new File(xmlFile.getParent()+File.separator+"metadata.xml");
                archiveData = XMLtoJsonUtils.startXMLToJSON(juanXml);
                archiveInfo = archiveData.getJSONObject("案卷级信息");
            }else {
                archiveInfo = archiveData.getJSONObject("案卷级信息");
            }
            Map<String,String> colData = new HashMap<>();
            //根据元数据解析节点
            colData.putAll(getValByMdataList(colData,archiveInfo,mdataLists,1,tenantCode));
            folderId = SnowflakeIdGenerator.generateId();
            colData.put("ID", String.valueOf(folderId));
            colData.put("IS_DEL","0");
            colData.put("IS_INDEX","0");
            colData.put("STATE","1");
            colData.put("JS_TYPE","1");  //在线移交
            colData.put("QZH",category.getFondsCode());
            colData.put("TYPE",category.getCode());
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(colData);
            folder.setTableName(category.getFolderTableName());
            folderMapper.insertYqFolderDisperse(folder); //插入分表

            colData.put("SUB_TABLE_NAME", category.getFolderTableName());
            colData.remove("ID");
            colData.put("FOLDER_ID", String.valueOf(folderId));
            folder.setColNames(colData);
            folder.setTableName(tenantCode+TenantYqFolder.BIGTABLENAME);
            int r = folderMapper.insertYqFolder(folder); //插入总表

            if(itemId !=null){
                //添加关联关系
                TenantItemFolder itemFolder = new TenantItemFolder();
                itemFolder.setItemId(itemId);
                itemFolder.setFolderId(folderId);
                itemFolder.setTableName(tenantCode+TenantItemFolder.BIGTABLENAME);
                itemFolderMapper.addItemFolder(itemFolder);
            }
        }
        JSONArray fileList = null;
        if(archiveType == 2 || archiveType == 1){
            fileList = archiveData.getJSONArray("卷内级信息");
        }else {
            fileList = new JSONArray();
            fileList.add(archiveData.getJSONObject("文件目录"));
        }


        for(int i = 0;i<fileList.size();i++){
            JSONObject archiveInfo = fileList.getJSONObject(i);
            Map<String,String> colData = new HashMap<>();
            //根据元数据解析节点
            colData.putAll(getValByMdataList(colData,archiveInfo,mdataLists,0,tenantCode));
            Long daId = SnowflakeIdGenerator.generateId();
            colData.put("ID", String.valueOf(daId));
            colData.put("IS_DEL","0");
            colData.put("IS_INDEX","0");
            colData.put("STATE","1");
            colData.put("JS_TYPE","1");  //在线移交
            colData.put("QZH",category.getFondsCode());
            colData.put("TYPE",category.getCode());
            colData.put("CREATE_TIME", DateUtils.getTime());
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(colData);
            yqda.setTableName(category.getFileTableName());
            yqdaMapper.insertYqdaDisperse(yqda); //插入分表

            colData.put("SUB_TABLE_NAME", category.getFileTableName());
            colData.remove("ID");
            colData.put("DA_ID", String.valueOf(daId));
            yqda.setColNames(colData);
            yqda.setTableName(tenantCode+TenantYqda.BIGTABLENAME);
            int r = yqdaMapper.insertYqda(yqda); //插入总表

            //插入关联关系
            if(archiveType == 2 || archiveType == 1){
                TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
                yqdaFolder.setDaId(daId);
                yqdaFolder.setFolderId(folderId);
                yqdaFolder.setItemId(itemId);
                yqdaFolder.setTableName(tenantCode+TenantYqdaFolder.BIGTABLENAME);
                yqdaFolderMapper.addYqdaFolder(yqdaFolder);

            }

            //解析电子文件
            int efileCount = saveEFile(xmlFile,archiveType,archiveInfo,msg,daId,category,tenantCode,mdataLists);
            //更新电子文件数量
            tenantYqdaMapper.updateYqdaOneColumn(tenantCode+TenantYqda.BIGTABLENAME,"EFILE_COUNT",String.valueOf(efileCount),daId);
            tenantYqdaMapper.updateYqdaOneColumnDisperse(category.getFileTableName(),"EFILE_COUNT",String.valueOf(efileCount),daId);
            //解析过程信息
            analysisProcessInfo(archiveData,daId,tenantCode,archiveType);
        }
    }


    private int saveEFile(File xmlFile,Integer archiveType,JSONObject archiveData,JSONObject msg,Long daId,TenantCategory category,String tenantCode,List<TenantMdataList> mdataLists) throws Exception{
        File eFile = null;
        if(archiveType == 2 || archiveType == 1){
            String path = xmlFile.getParent() + File.separator + archiveData.getString("卷内ID")+ File.separator;
            eFile = new File(path);
        }else {
            eFile = xmlFile.getParentFile();
        }

        int r = 0;
        Object o = archiveData.getJSONObject("电子属性集").get("电子属性");;
        JSONArray efileJson = new JSONArray();
        if(o instanceof JSONObject){
            efileJson.add(o);
        }else if(o instanceof JSONArray){
            efileJson = (JSONArray)o;
        }
        TenantSysConfig config = new TenantSysConfig();
        config.setTenantCode(tenantCode);
        config.setConfigKey("YQ_MNT");
        String baseDir = tenantSysConfigMapper.selectConfig(config).getConfigValue();  //保存位置
        for(int i = 0;i<efileJson.size();i++){
            JSONObject efileData = efileJson.getJSONObject(i);
            Map<String,String> colNum = new HashMap<>();
            //根据元数据解析节点
            colNum.putAll(getValByMdataList(colNum,efileData,mdataLists,2,tenantCode));
            //验证必要内容
            if(!colNum.containsKey("DOC_NAME") || !colNum.containsKey("TYPE") || !colNum.containsKey("DOC_FILE_TYPE") || !colNum.containsKey("REAL_DOC_NAME")){
                throw new ServiceException("电子文件层缺少必要参数！");
            }
            String type = colNum.get("TYPE");
            String docFileType = colNum.get("DOC_FILE_TYPE");
            String docName = colNum.get("REAL_DOC_NAME");
            //支持格式转换服务的文件类型
            boolean isAgentCompressedFiles = TokenParamUtil.isIsAgentCompressedFiles();
            if(isAgentCompressedFiles){
                String agentFileTypes = "ofd,pdf,doc,docx,eid,rtf,dot,docm,dotm,dotx,wps,wpt,txt,xml,xps,ppt,pptx,eip,ppsm,potm,potx,pps,pot,dpt,ppsx,dpsxls,xlsx,et,eis,xlt,xlsb,ett,xlsm,xltx,xla,xlam,xltm,jpg,jpeg,png,bmp,jp2,tif,tiff, gif,html,url,htm,html";
                if(!agentFileTypes.contains(colNum.get("DOC_FILE_TYPE").toLowerCase())){
                    throw new ServiceException(docName+"，该文件类型不支持归档,请解压后上传！");
                }
            }
            TenantYqdaDocument document = new TenantYqdaDocument();
            document.setConTableId(daId);
            document.setTableName(category.getEfileTableName());
            String orderNoStr = tenantYqdaDocumentMapper.MaxOrderNo(document);
            int orderNo =  StringUtils.isEmpty(orderNoStr) ? 1:(Integer.valueOf(orderNoStr)+1); //文件顺序
            String fileName = extractFilename(type,daId,orderNo,docFileType);  //保存文件名
            File xmlPath = new File(eFile+File.separator+docName);  //归档包电子文件路径
            if(!xmlPath.exists()){
                logger.error(xmlPath.getAbsolutePath()+xmlPath.getName());
                throw new ServiceException(docName+"。文件获取失败！");
            }
            String filePath = extractPath(category,daId);  //存储的相对路径
            String absPath = getAbsoluteFile(baseDir+filePath, fileName).getAbsolutePath();  //保存文件位置  绝对路径
            FileUtils.copyFile(xmlPath,new File(absPath));  //复制文件
            // 获取文件属性
            BasicFileAttributes attributes = Files.readAttributes(Paths.get(absPath), BasicFileAttributes.class);
            // 获取文件创建时间
            FileTime createTime = attributes.creationTime();
            // 将文件创建时间转换为标准格式
            String dateFormat = df.format(createTime.toMillis());
            TenantYqdaDocument saveDocument = new TenantYqdaDocument();
            colNum.put("PATH",filePath+fileName);
            colNum.put("DOC_ORDER", String.valueOf(orderNo));
            //colNum.put("DOC_NAME",showName);
            colNum.put("DOC_FILE_TYPE", docFileType.toUpperCase());
            colNum.put("IS_DEL","0");
            colNum.put("ACTION_TIME",dateFormat);
            colNum.put("CREATE_TIME", DateUtils.getTime());
            colNum.put("DOC_FILE_SIZE", String.valueOf(attributes.size()));
            colNum.put("IS_INDEX","0");
            colNum.put("TYPE",type);
            colNum.put("REAL_DOC_NAME",fileName);
            colNum.put("DOC_MNT",baseDir);
            colNum.put("DOC_CREATE_TIME", FileUploadUtils.getDocCreateTime(new File(absPath)));
            colNum.put("FILE_ONLY_VAL", WebServiceFileUtils.getFileMD5(new File(absPath)));
            saveDocument.setColNames(colNum);
            saveDocument.setTableName(category.getEfileTableName());
            saveDocument.setDocId(SnowflakeIdGenerator.generateId());
            saveDocument.setConTableId(daId);
            r = r + tenantYqdaDocumentMapper.insertDocument(saveDocument);
        }
        return r;
    }

    private final String extractPath(TenantCategory category,Long daId)
    {
        StringBuilder path = new StringBuilder().append(category.getFondsCode()).append(File.separator).append(category.getCode()).append(File.separator).
                append(daId).append(File.separator);
        return path.toString();
    }

    private String extractFilename(String type ,Long daId,int orderNo, String docFileType)
    {
        String fileName = daId+"0"+type+"A"+ (orderNo<999 ? (orderNo<99 ? (orderNo<9 ? "00"+orderNo:("0"+orderNo)):orderNo):orderNo);
        StringBuilder path = new StringBuilder().append(fileName).append(".").append(docFileType);
        return path.toString();
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private void analysisProcessInfo(JSONObject info,Long daId,String tenantCode,Integer archiveType) throws Exception{
        JSONArray processArray = new JSONArray();
        if(archiveType == 2 || archiveType == 1){
            Object daInfo = info.get("卷内级信息");
            if(daInfo instanceof JSONObject){
                JSONObject object = (JSONObject)daInfo;
                Object o = object.getJSONObject("过程信息集").get("过程信息");
                if(o instanceof JSONObject){
                    processArray.add((JSONObject)o);
                }else if(o instanceof JSONArray){
                    processArray = (JSONArray)o;
                }
            }else if(daInfo instanceof JSONArray){
                JSONArray array = (JSONArray)daInfo;
                for(int i = 0;i<array.size();i++){
                    Object o = array.getJSONObject(i).getJSONObject("过程信息集").get("过程信息");
                    if(o instanceof JSONObject){
                        processArray.add((JSONObject)o);
                    }else if(o instanceof JSONArray){
                        JSONArray karr = (JSONArray) o;
                        for(int k = 0;k<karr.size();k++){
                            processArray.add(karr.getJSONObject(k));
                        }
                    }
                }
            }

        }else if(archiveType == 0){
            if(info.getJSONObject("文件目录").getJSONObject("过程信息集")!=null){
                Object processInfo = info.getJSONObject("文件目录").getJSONObject("过程信息集").get("过程信息");
                if(processInfo instanceof JSONObject){
                    processArray.add(processInfo);
                }else if(processInfo instanceof  JSONArray){
                    processArray = (JSONArray)processInfo;
                }
            }
        }

        for(int i = 0;i<processArray.size();i++){
            JSONObject object = processArray.getJSONObject(i);
            String name = object.getString("处理类型");
            //BusinessBehavior businessBehavior = BusinessBehavior.valueOf(name, 0);
            BusinessActivity businessActivity = new BusinessActivity();
            businessActivity.setCode(-1);
            businessActivity.setName(name);
            businessActivity.setUserName(object.getString("处理人员"));
            Date date = null;
            if(StringUtils.isNotEmpty(object.getString("处理时间"))){
                date = object.getDate("处理时间");
            }
            businessActivity.setActionTime(date);
            businessActivity.setDept(object.getString("处理部门"));
            businessActivity.setDaId(daId);
            //businessActivity.setUserId(sysUser.getUserId());
            //businessActivity.setDeptId(sysUser.getDept().getDeptId());
            businessActivity.setTableName(tenantCode+"_BUSINESSACTIVITY");
            asyncLogService.saveBusinessBehavior(businessActivity);
        }
    }
}
